package com.dongdongshop.controller;

import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.seckill.TbSeckillGoods;
import com.dongdongshop.service.seckill.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 秒杀
 * @Author Eayon
 * @Date 2020/4/5 14:59
 */
@RequestMapping("seckill")
@RestController
public class SeckillController {

    @Autowired
    private SeckillService seckillService;

    private static final Logger log = LoggerFactory.getLogger(SeckillController.class);

    /**
     * 查询所有状态正常的秒杀商品
     * @return
     */
    @GetMapping("/findSeckillGoodsAll")
    public DataResult<List<TbSeckillGoods>> findSeckillGoodsAll(){
        List<TbSeckillGoods> seckillGoodsList = null;
        try {
            seckillGoodsList = seckillService.findSeckillGoodsAll();
        }catch (Exception e){
            log.error("查询所有秒杀商品异常",e);
            return new DataResult<List<TbSeckillGoods>>(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult<List<TbSeckillGoods>>(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),seckillGoodsList);
    }

    /**
     * 根据秒杀商品id查询秒杀商品信息(从缓存中查询)
     * @param id
     */
    @GetMapping("/getSeckillById/{id}")
    public DataResult<TbSeckillGoods> getSeckillById(@PathVariable("id") Long id){
        TbSeckillGoods seckillGoods = null;
        try {
            seckillGoods = seckillService.getSeckillById(id);
        }catch (Exception e){
            log.error("根据秒杀商品id查询秒杀商品信息异常",e);
            return new DataResult<TbSeckillGoods>(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult<TbSeckillGoods>(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),seckillGoods);
    }


    /**
     * 创建秒杀订单
     * @return
     */
    @PostMapping("/createSeckillOrder")
    public DataResult createSeckillOrder(@RequestParam("seckillId")Long seckillId,@RequestParam("userId")Long userId){
        try {
            seckillService.createSeckillOrder(seckillId,userId);
        }catch (RuntimeException e){
            log.error("异常"+e);
            return new DataResult(HttpResultEnum.ERROR.getCode(),"你已经秒杀过该商品，或该商品库存不足");
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),"抢购成功，等待付款");
    }
}
